const state = {
  // json.parse 把字符串转化为对象
  // 哪里设置cart 的本地存储呢？
  // 状态改变后去同步设置更新 localStorage，使用插件可以做到
  cartProducts: JSON.parse(window.localStorage.getItem('cart-products')) || []
}
const getters = {
  totalNum (state) {
    return state.cartProducts.reduce((total, current) => total + current.count, 0)
  },
  totalPrice (state) {
    return state.cartProducts.reduce((total, current) => total + current.totalPrice, 0)
  },
  checkedNum (state, getters) {
    return getters.isCheckedPro.reduce((total, current) => total + current.count, 0)
  },
  checkedPrice (state, getters) {
    return getters.isCheckedPro.reduce((total, current) => total + current.totalPrice, 0)
  },
  isCheckedPro (state) {
    return state.cartProducts.filter(item => item.isChecked)
  }
}
const mutations = {
  addToCart (state, payload) {
    const _product = state.cartProducts.find(({ id }) => id === payload.id)
    if (_product) {
      _product.count++
      _product.isChecked = true
      _product.totalPrice = (_product.count * _product.price).toFixed(2)
    } else {
      state.cartProducts.push({
        ...payload,
        count: 1,
        isChecked: true,
        totalPrice: payload.price
      })
    }
  },
  deleteCartProduct (state, payload) {
    const idx = state.cartProducts.findIndex(({ id }) => id === payload.id)
    state.cartProducts.splice(idx, 1)
  },
  checkedAllProducts (state, isChecked) {
    state.cartProducts.forEach(item => { item.isChecked = isChecked })
  },
  checkedProduct (state, { isChecked, prodId }) {
    const item = state.cartProducts.find(item => item.id === prodId)
    item && (item.isChecked = isChecked)
  },
  updateCount (state, { count, prodId }) {
    const item = state.cartProducts.find(item => item.id === prodId)
    if (item) {
      item.count = count
      item.totalPrice = (count * item.price).toFixed(2)
    }
  }
}
const actions = {}

export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions
}
